package com.hk.common.shiro.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hk.common.constant.Constants;
import com.hk.common.redis.Redis;
import com.hk.modules.user.pojo.UserPojo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;


/**
 * @author zhangyu
 * @date 2019-11-04
 */
@Component
public class JwtTokenUtil implements Serializable {
    private Logger log = LoggerFactory.getLogger(JwtTokenUtil.class);

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.captcha}")
    private boolean captcha;

    @Autowired
    private Redis redis;

    public String generateToken(String account) {
        Date date = new Date(System.currentTimeMillis() + expiration * 60 * 1000L);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create().
                withClaim("username", account)
                .withExpiresAt(date).sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token   密钥
     * @param account 用户的密码
     * @return 是否正确
     */
    public String verify(String token, String account) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", account).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return token;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public String getUserName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息 用户信息
     * @return token中包含的用户名
     */
    public UserPojo getUserInfo(HttpServletRequest request) {
        try {
            String token = request.getHeader(tokenHeader);
            DecodedJWT jwt = JWT.decode(token);
            String userName = jwt.getClaim("username").asString();
            UserPojo user = redis.getObject(redis.prefixKey(Constants.USER_PREFIX,userName));
            return user;
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    public Long getExp(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("exp").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }



    public boolean getCaptcha() {
        return captcha;
    }

    public void setCaptcha(boolean captcha) {
        this.captcha = captcha;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public Long getExpiration() {
        return expiration;
    }

    public void setExpiration(Long expiration) {
        this.expiration = expiration;
    }

    public String tokenHeader() {
        return tokenHeader;
    }
}
